package com.pesking.core.sqlparser.processor;

import java.util.*;

import com.pesking.core.parameter.Parameter;
import com.pesking.core.sqlparser.parameter.SqlParameter;
import com.pesking.core.sqlparser.parameter.SqlParameterProcessor;
import com.pesking.core.util.StringUtils;

public class InStringSqlParameterHandler extends SqlParameterProcessor {

	
	@Override
	public void handle(StringBuilder sbSQL, Parameter parameter, List<SqlParameter> processors,SqlParameter sqlParameter) {
		String name = sqlParameter.getName();
		String []values = parameter.getParameterValues(name);
		
		if (values == null || values.length == 0){
			sbSQL.append("(null)");
		}
		else{
			int len = values.length;
			boolean first = true;
			Set<String> set = new HashSet<>();
			for(int i = 0 ; i < len ; i++){
				set.add(values[i]);
			}
			Iterator<String> it = set.iterator();
			while(it.hasNext()) {
				String v = it.next();
				if (!StringUtils.isBlank(v)){
					v = formatValue(v);
					if (first){
						first = false;
						sbSQL.append("('").append(v).append("'");
					}
					else{
						sbSQL.append(",'").append(v).append("'");
					}
				}
			}
			
			if (first){
				sbSQL.append("(null)");
			}
			else{
				sbSQL.append(")");
			}
		}
	}

	@Override
	public List<String> getSqlParameterType() {
		return Arrays.asList(new String []{"IN_S"});
	}

}
